import { defineStore } from 'pinia'

export const useUserStore = defineStore('user', {
  state: () => ({
    userInfo: null,
    token: localStorage.getItem('token') || null,
    tokenBalance: localStorage.getItem('tokenBalance') ? Number(localStorage.getItem('tokenBalance')) : 0,
    bankAccount: localStorage.getItem('bankAccount') || '',
    bankName: localStorage.getItem('bankName') || '',
    transactionHistory: JSON.parse(localStorage.getItem('transactionHistory') || '[]')
  }),
  
  getters: {
    isLoggedIn: (state) => !!state.token,
    isCompany: (state) => state.userInfo?.role === 'company',
    isWorker: (state) => state.userInfo?.role === 'worker'
  },
  
  actions: {
    setUserInfo(userInfo) {
      this.userInfo = userInfo
    },
    
    setToken(token) {
      this.token = token
      if (token) {
        localStorage.setItem('token', token)
      } else {
        localStorage.removeItem('token')
      }
    },
    
    setBankInfo(bankName, bankAccount) {
      this.bankName = bankName
      this.bankAccount = bankAccount
      localStorage.setItem('bankName', bankName)
      localStorage.setItem('bankAccount', bankAccount)
    },
    
    // 充值代币
    depositTokens(amount) {
      const parsedAmount = Number(amount)
      if (isNaN(parsedAmount) || parsedAmount <= 0) {
        throw new Error('无效的代币数量')
      }
      
      this.tokenBalance += parsedAmount
      localStorage.setItem('tokenBalance', this.tokenBalance.toString())
      
      // 记录交易历史
      const transaction = {
        id: Date.now().toString(),
        type: 'deposit',
        amount: parsedAmount,
        date: new Date().toISOString(),
        status: 'completed'
      }
      
      this.transactionHistory.push(transaction)
      localStorage.setItem('transactionHistory', JSON.stringify(this.transactionHistory))
      
      return transaction
    },
    
    // 提现代币
    withdrawTokens(amount) {
      const parsedAmount = Number(amount)
      if (isNaN(parsedAmount) || parsedAmount <= 0) {
        throw new Error('无效的代币数量')
      }
      
      if (parsedAmount > this.tokenBalance) {
        throw new Error('代币余额不足')
      }
      
      if (!this.bankAccount || !this.bankName) {
        throw new Error('请先绑定银行账户')
      }
      
      this.tokenBalance -= parsedAmount
      localStorage.setItem('tokenBalance', this.tokenBalance.toString())
      
      // 记录交易历史
      const transaction = {
        id: Date.now().toString(),
        type: 'withdraw',
        amount: parsedAmount,
        date: new Date().toISOString(),
        status: 'processing',
        bankInfo: {
          name: this.bankName,
          account: this.bankAccount
        }
      }
      
      this.transactionHistory.push(transaction)
      localStorage.setItem('transactionHistory', JSON.stringify(this.transactionHistory))
      
      // 模拟异步处理
      setTimeout(() => {
        const updatedHistory = this.transactionHistory.map(item => {
          if (item.id === transaction.id) {
            return { ...item, status: 'completed' }
          }
          return item
        })
        
        this.transactionHistory = updatedHistory
        localStorage.setItem('transactionHistory', JSON.stringify(this.transactionHistory))
      }, 2000)
      
      return transaction
    },
    
    logout() {
      this.userInfo = null
      this.token = null
      // 不清除代币余额和交易记录，以便用户再次登录时可以恢复
      localStorage.removeItem('token')
    }
  }
}) 